import asyncio
import json
import logging
import os
import platform
import signal
import subprocess
import sys
import time

import requests
from agent_client import AgentClient, AgentTask

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


class AgentRunner:
    def __init__(self):
        self.server_process = None
        self.ollama_url = "http://localhost:11434"
        self.server_url = "http://localhost:8000"
        self.model_name = "qwen3:8b"

    def check_ollama_service(self):
        """检查 Ollama 服务状态"""
        try:
            response = requests.get(f"{self.ollama_url}/api/tags")
            if response.status_code == 200:
                logger.info("Ollama 服务正在运行")
                return True
            return False
        except requests.exceptions.ConnectionError:
            logger.error("Ollama 服务未运行")
            return False

    def check_model_availability(self):
        """检查模型是否可用"""
        try:
            response = requests.get(f"{self.ollama_url}/api/tags")
            if response.status_code == 200:
                models = response.json().get("models", [])
                if any(model["name"] == self.model_name for model in models):
                    logger.info(f"模型 {self.model_name} 已安装")
                    return True
                else:
                    logger.error(f"模型 {self.model_name} 未安装")
                    return False
            return False
        except requests.exceptions.ConnectionError:
            return False

    def start_server(self):
        """启动服务器"""
        try:
            # 使用 Python 解释器启动服务器
            if platform.system() == "Windows":
                self.server_process = subprocess.Popen(
                    [sys.executable, "agent_server.py"],
                    creationflags=subprocess.CREATE_NEW_CONSOLE
                )
            else:
                self.server_process = subprocess.Popen(
                    [sys.executable, "agent_server.py"],
                    preexec_fn=os.setsid
                )

            # 等待服务器启动
            for _ in range(30):  # 最多等待30秒
                try:
                    response = requests.get(f"{self.server_url}/v1/model/status")
                    if response.status_code == 200:
                        logger.info("服务器启动成功")
                        return True
                except requests.exceptions.ConnectionError:
                    time.sleep(1)
                    continue

            logger.error("服务器启动超时")
            return False
        except Exception as e:
            logger.error(f"启动服务器失败: {str(e)}")
            return False

    def stop_server(self):
        """停止服务器"""
        if self.server_process:
            try:
                if platform.system() == "Windows":
                    self.server_process.terminate()
                else:
                    os.killpg(os.getpgid(self.server_process.pid), signal.SIGTERM)
                self.server_process.wait(timeout=5)
                logger.info("服务器已停止")
            except Exception as e:
                logger.error(f"停止服务器失败: {str(e)}")
                if platform.system() == "Windows":
                    subprocess.run(['taskkill', '/F', '/T', '/PID', str(self.server_process.pid)])
                else:
                    os.killpg(os.getpgid(self.server_process.pid), signal.SIGKILL)

    async def test_model(self):
        """测试模型功能"""
        try:
            client = AgentClient()
            # 测试任务
            task = AgentTask(
                task_type="test",
                parameters={
                    "text": "你好，请用一句话介绍一下你自己"
                }
            )

            logger.info("开始测试模型...")
            result = await client.execute_single_task(task)
            logger.info("模型测试结果:")
            print(json.dumps(result, ensure_ascii=False, indent=2))
            return True
        except Exception as e:
            logger.error(f"模型测试失败: {str(e)}")
            return False

    def run(self):
        """运行完整流程"""
        try:
            # 1. 检查 Ollama 服务
            logger.info("检查 Ollama 服务...")
            if not self.check_ollama_service():
                logger.error("请先启动 Ollama 服务")
                return False

            # 2. 检查模型
            logger.info("检查模型状态...")
            if not self.check_model_availability():
                logger.error(f"请先安装模型: ollama pull {self.model_name}")
                return False

            # 3. 启动服务器
            logger.info("启动服务器...")
            if not self.start_server():
                return False

            # 4. 运行测试
            logger.info("运行模型测试...")
            if not asyncio.run(self.test_model()):
                return False

            logger.info("所有测试通过！系统运行正常。")
            return True

        except KeyboardInterrupt:
            logger.info("接收到中断信号，正在停止服务...")
            return False
        except Exception as e:
            logger.error(f"运行过程出错: {str(e)}")
            return False
        finally:
            self.stop_server()


if __name__ == "__main__":
    runner = AgentRunner()
    success = runner.run()
    sys.exit(0 if success else 1)
